<script setup lang="ts">
import type { DataAction } from '../DataForm/types'
import { computed, ref } from 'vue'
import { hasAnyAuth } from '@/utils/authUtil'
import { doDataAction } from '../DataForm/types'

const { action } = defineProps<{
  action: DataAction | DataAction[]
}>()
const model = defineModel<Partial<any>>()

const actions = computed(() => {
  const result = Array.isArray(action) ? action : [action]
  return result.filter(a => a.authCode === undefined || hasAnyAuth(a.authCode))
})

const clickLoading = ref(false)
async function onClick(action: DataAction) {
  if (clickLoading.value === true) {
    return
  }
  clickLoading.value = true
  try {
    await doDataAction(model.value, action)
  }
  finally {
    clickLoading.value = false
  }
}
</script>

<template>
  <el-button
    v-if="actions.length === 1"
    :type="typeof actions[0].type === 'function' ? actions[0].type(model) : actions[0].type"
    :loading="clickLoading"
    @click="onClick(actions[0])"
  >
    {{ (typeof actions[0].label === 'function') ? actions[0].label(model) : actions[0].label }}
  </el-button>

  <el-dropdown
    v-if="actions.length > 1"
    split-button
    :type="typeof actions[0].type === 'function' ? actions[0].type(model) : actions[0].type"
    @click="onClick(actions[0])"
    @command="(index) => onClick(actions[index])"
  >
    {{ (typeof actions[0].label === 'function') ? actions[0].label(model) : actions[0].label }}
    <template #dropdown>
      <el-dropdown-menu>
        <template v-for="(a, index) in actions" :key="index">
          <el-dropdown-item v-if="index > 1" :command="index">
            <el-text :type="typeof a.type === 'function' ? a.type(model) : a.type ">
              {{ (typeof a.label === 'function') ? a.label(model) : a.label }}
            </el-text>
          </el-dropdown-item>
        </template>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>
